import multer from 'multer';
import path from 'path';
import ffmpeg from "fluent-ffmpeg";
import sharp from "sharp";
import { v4 as uuidv4 } from 'uuid';
import { FILE_SIZE_LIMIT, FILE_UPLOAD_DIR } from '../constants/normal.constants';
ffmpeg.setFfmpegPath(process.env.FFMPEG_PATH);


// 配置存储
const storage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, FILE_UPLOAD_DIR),
    filename: (req, file, cb) => {
        const ext = path.extname(file.originalname).toLowerCase();
        const uuid = uuidv4();
        cb(null, uuid + ext); // 文件名本身就是 UUID
    }
});

// 创建 Multer 实例
const upload = multer({
    storage,
    limits: { fileSize: FILE_SIZE_LIMIT }
});

const uploadFile = upload.single('file');
export default uploadFile


export function generateVideoThumbnail(videoPath: string, outputPath: string): Promise<string> {
    const folder = path.dirname(outputPath);
    const filename = path.basename(outputPath);
    return new Promise((resolve, reject) => {
        ffmpeg(videoPath)
            .screenshots({
                timestamps: ["00:00:01"],
                filename,
                folder,
                size: "320x240",
            })
            .on("end", () => resolve(outputPath))
            .on("error", (err) => {
                console.error("生成缩略图失败:", err);
                reject(err);
            });
    });
}

export function generateImageThumbnail(inputPath: string, outputPath: string) {
    return sharp(inputPath).resize(200).jpeg({ quality: 80 }).toFile(outputPath);
}

export function generateVideoHls(filePath: string, hlsPath: string): Promise<string> {
    return new Promise((resolve, reject) => {
        ffmpeg(filePath)
            .output(hlsPath)
            .outputOptions([
                '-hls_list_size 0',    // 保留所有片段
                '-hls_time 10',        // 每个分片约10秒
                '-f hls'               // 指定输出格式为HLS
            ])
            .on('end', () => {
                resolve(hlsPath);
            })
            .on('error', (err) => {
                reject(err);
            })
            .run();
    })
}
